# encoding: utf-8
import datetime

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from utils.BaseModel import BaseModel

from itsdangerous import TimedJSONWebSignatureSerializer


class UserProfile(AbstractUser):
    """
    用户
    """
    GENDER_CHOICES = (
        ('female', '女'),
        ('male', '男'),
    )
    name = models.CharField(verbose_name="姓名", max_length=30, null=True, blank=True)
    birthday = models.DateField(verbose_name="出生年月", null=True, blank=True)
    gender = models.CharField(verbose_name="性别", max_length=6, choices=GENDER_CHOICES, default='female')
    mobile = models.CharField(verbose_name="手机号码", max_length=11, null=True, blank=True, unique=True,)
    email = models.EmailField(verbose_name="邮箱", max_length=100, null=True, blank=True)

    email_active = models.BooleanField(default=False,
                                       verbose_name='邮箱验证状态')
    default_address = models.ForeignKey(
        'Address',
        related_name='users',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        verbose_name='默认地址'
    )

    class Meta:
        verbose_name = "用户"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

    def generate_verify_email_url(self):

        # 针对不同的用户生产不同的token值
        serializer = TimedJSONWebSignatureSerializer(
            settings.SECRET_KEY,
            expires_in=60 * 60 * 24,  # 激活链接中token的有效期
        )

        data = {
            "user_id": self.id,
            "email": self.email
        }

        token = serializer.dumps(data).decode()

        verify_url = settings.EMAIL_VERIFY_URL + token

        return verify_url

    # @classmethod
    # def check_token(cls, token):
    @staticmethod
    def check_verify_email_token(token):
        """
        验证token，并且获取用户对像返回
        """
        # from itsdangerous import TimedJSONWebSignatureSerializer
        # from django.conf import settings

        serializer = TimedJSONWebSignatureSerializer(settings.SECRET_KEY,expires_in=60 * 60 * 24)

        try:
            # payload = serializer.loads(token)
            data = serializer.loads(token)
        except Exception as e:
            print(e)
            return None  # token验证失败
        else:
            user_id = data.get('user_id')
            email = data.get('email')

        try:
            user = UserProfile.objects.get(pk=user_id, email=email)
        except Exception as e:
            print(e)
            return None
        else:
            return user


class VerifyCode(models.Model):
    """
    短信验证码
    """
    code = models.CharField(verbose_name="验证码", max_length=10)
    mobile = models.CharField(verbose_name="手机号码", max_length=11)
    add_time = models.DateTimeField(verbose_name="添加时间", default=datetime.datetime.now)

    class Meta:
        verbose_name = "短信验证码"
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.code


# 以下是meiduo的user

# 设置密码
# User.set_password()
# 验证密码
# User.check_password()
# from django.contrib.auth import authenticate
# authenticate(username=xxx, password=xxxx)传入用户名和密码，传统身份认证
# 密码不会自动加密
# User.objects.create(username=xxx, password=xxx)
# 密码自动加密
# User.objects.create_user(username=xx, password=xx)
# is_authenticated == True  ： 该用户经过身份认证(有身份)
# User.is_authenticated
# from django.contrib.auth.models import AnonymousUser
# AnonymousUser() ---> 匿名用户对象  ---> django默认的身份认证后端验证用户失败，统一返回匿名用户对象
# AnonymousUser().is_authenticated --> False


class Address(BaseModel):
    user = models.ForeignKey(
        UserProfile,
        on_delete=models.CASCADE,
        related_name='addresses',
        verbose_name='用户'
    )
    province = models.ForeignKey(
        'areas.Area',
        on_delete=models.PROTECT,
        related_name='province_addresses',
        verbose_name='省'
    )
    city = models.ForeignKey(
        'areas.Area',
        on_delete=models.PROTECT,
        related_name='city_addresses',
        verbose_name='市'
    )
    district = models.ForeignKey(
        'areas.Area',
        on_delete=models.PROTECT,
        related_name='district_addresses',
        verbose_name='区'
    )
    title = models.CharField(max_length=20, verbose_name='地址名称')
    receiver = models.CharField(max_length=20, verbose_name='收货人')
    place = models.CharField(max_length=50, verbose_name='地址')
    mobile = models.CharField(max_length=11, verbose_name='手机')
    tel = models.CharField(max_length=20,
                           null=True,
                           blank=True,
                           default='',
                           verbose_name='固定电话')

    email = models.CharField(max_length=30,
                             null=True,
                             blank=True,
                             default='',
                             verbose_name='电子邮箱')

    is_deleted = models.BooleanField(default=False, verbose_name='逻辑删除')

    class Meta:
        db_table = 'md_address'
        verbose_name = '用户地址'
        verbose_name_plural = verbose_name
        ordering = ['-update_time']

